package com.thlws.study.redismq.controller;

import cn.hutool.core.util.RandomUtil;
import com.thlws.study.redismq.internal.MessageSender;
import com.thlws.study.redismq.internal.helper.RedisMqHelper;
import com.thlws.study.redismq.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @author HanleyTang 2019-07-31
 */
@RestController
public class IndexController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final MessageSender sender;

    private final RedisMqHelper redisHelper;

    public IndexController(MessageSender sender, RedisMqHelper redisHelper) {
        this.sender = sender;
        this.redisHelper = redisHelper;
    }

    @RequestMapping("/")
    public Object time(){
        return LocalDateTime.now();
    }

    @RequestMapping("/send")
    public Object send(){
        sender.sendMessage();
        return LocalDateTime.now();
    }

    @RequestMapping("/send0")
    public Object send0(@RequestParam(name = "chnanel") String chnanel){
        sender.sendMessage(chnanel,"我是 ["+chnanel+"] 一套");
        return LocalDateTime.now();
    }

    @RequestMapping("/send1")
    public Object send1(){
        sender.sendMessage("cctv-1","我是中央一套");
        return LocalDateTime.now();
    }

    @RequestMapping("/send2")
    public Object send2(){
        sender.sendMessage("cctv-2","我是中央二套");
        return LocalDateTime.now();
    }


    @RequestMapping("/send3")
    public Object send3(){
        sender.sendMessage("cctv-3","我是中央三套");
        return LocalDateTime.now();
    }


    @RequestMapping("/push")
    public Object push(){
        sender.pushMessage("redis queue 数据:"+RandomUtil.randomString(5));
        return LocalDateTime.now();
    }



    /**=====================================*/


    @RequestMapping("/sub")
    public Object sub(){

        redisHelper.subscribe("cctv",(msg)-> logger.info("收到消息: {} ",msg));

        return "订阅CCTV成功";
    }

    @RequestMapping("/unsub")
    public Object unsub(){
        redisHelper.unsubscribe("cctv");
        return "取消订阅CCTV";
    }



    @RequestMapping("/set")
    public Object set(){

        redisHelper.set("cctv",new User(RandomUtil.randomString(5),"阆中",RandomUtil.randomInt(100)));
        return LocalDateTime.now();
    }

    @RequestMapping("/get")
    public User get(){
        return redisHelper.get("cctv",User.class);
    }

}
